Component({
  properties: {
    list: {
      type: Array,
      value: [],
      observer: function(newVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(this._lastList)) {
          this._lastList = newVal.slice()
          this.initWaterFall()
        }
      }
    }
  },

  data: {
    leftList: [],
    rightList: [],
    hasNoMoreData: false
  },

  methods: {
    initWaterFall() {
      this.leftHeight = 0
      this.rightHeight = 0
      this.setData({
        leftList: [],
        rightList: [],
        hasNoMoreData: false
      }, () => this.processItems(0))
    },

    async processItems(index) {
      // 结束条件判断
      if (index >= this.properties.list.length) {
        this.checkCompletion()
        return
      }

      const item = this.properties.list[index]
      const targetColumn = this.leftHeight <= this.rightHeight ? 'leftList' : 'rightList'

      this.data[targetColumn].push(item)
      this.setData({ [targetColumn]: this.data[targetColumn] }, () => {
        // 在setData回调中检查完成状态
        this.checkCompletion()
      })

      await new Promise(resolve => setTimeout(resolve, 50))
      await this.updateColumnsHeight()
      this.processItems(index + 1)
    },

    checkCompletion() {
      const total = this.data.leftList.length + this.data.rightList.length
      const isComplete = total === this.properties.list.length
      if (isComplete !== this.data.hasNoMoreData) {
        this.setData({ hasNoMoreData: isComplete })
      }
    },

    async updateColumnsHeight() {
      return new Promise(resolve => {
        const query = this.createSelectorQuery()
        query.select('.left-column').boundingClientRect()
        query.select('.right-column').boundingClientRect()
        query.exec(res => {
          this.leftHeight = res[0]?.height || 0
          this.rightHeight = res[1]?.height || 0
          resolve()
        })
      })
    }
  }
})
